package com.ccdt.tv.smartrecommend.presenter.SmartService;

import android.content.Intent;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.Utils;
import com.ccdt.tv.smartrecommend.Constant;
import com.ccdt.tv.smartrecommend.FromLiveBean;
import com.ccdt.tv.smartrecommend.model.bean.ResponseBean;
import com.ccdt.tv.smartrecommend.model.http.Api;
import com.ccdt.tv.smartrecommend.service.RecommendService;
import com.ccdt.tv.smartrecommend.utils.DVBServiceManager;
import com.ccdt.tv.smartrecommend.utils.GetTokenServiceHelper;
import com.google.gson.Gson;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by syt on 2018/9/10.
 * aidl service P层
 */

public class SmartServicePresenter extends SmartServiceContract.Presenter implements GetTokenServiceHelper.OnCaCardChanged, GetTokenServiceHelper.ServiceConnectListener {

    private static final String TAG = "SmartServicePresenter";
    private Gson mGson;
    private GetTokenServiceHelper mTokenServiceHelper;
    private Subscription mSubLiveRecommend;
    private Subscription mSubHitChannels;
    private DVBServiceManager mDVBServiceManager;

    @Override
    public void attachView(@NonNull SmartServiceContract.View view) {
        super.attachView(view);
        mGson = new Gson();
        //CA卡绑定服务
        mTokenServiceHelper = GetTokenServiceHelper.getInstance();
        mTokenServiceHelper.bind(Utils.getApp());
        mTokenServiceHelper.setOnCaCardChanged(this);
        mTokenServiceHelper.setServiceConnectListener(this);
        //绑定DVB服务
        mDVBServiceManager = DVBServiceManager.getInstance(Utils.getApp());
        mDVBServiceManager.bindService();
    }

    @Override
    public void createLiveRecommend() {
        finishLiveRecommend();
        //获取直播推荐
        //延时后每隔固定时间触发事件
        mSubLiveRecommend =
//                Observable.interval(5, 30, TimeUnit.SECONDS, Schedulers.trampoline())
                Observable.just(0L).delay(5, TimeUnit.SECONDS)   //有动作之后5秒显示
                        .subscribeOn(Schedulers.io())
                        .flatMap(new Func1<Long, Observable<ResponseBean>>() {
                            @Override
                            public Observable<ResponseBean> call(Long aLong) {
                                String liveJson = SPUtils.getInstance(Constant.SP_NAME).getString(Constant.SP_LIVE_JSON);
                                if (TextUtils.isEmpty(liveJson)) {
                                    Log.e(TAG, "doLiveRecommend: live json is null");
                                    return null;
                                }
                                FromLiveBean liveBean = mGson.fromJson(liveJson, FromLiveBean.class);
                                GetTokenServiceHelper.CaInfo caInfo = mTokenServiceHelper.getCaInfo();
                                Log.w(TAG, "call: caid：" + caInfo.caId + "--areaCode:" + caInfo.areaCode + "--serviceId:" + liveBean.getSid());
                                return Api.getInstance().getLiveRecommend(caInfo.caId, caInfo.areaCode, liveBean.getSid());
                            }
                        }).observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Action1<ResponseBean>() {
                            @Override
                            public void call(ResponseBean responseBean) {
                                if (null != responseBean) {
                                    Log.w(TAG, "getLiveRecommend: url:" + responseBean.getMsg());
                                    if (responseBean.getStatus() == 200 || responseBean.getStatus() == 600) {
                                        //启动 视图 service
                                        startService(responseBean.getMsg());
                                    } else {
                                        Log.w(TAG, "getLiveRecommend: status is error! status:" + responseBean.getStatus());
                                    }
                                }
                            }
                        }, new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                throwable.printStackTrace();
                            }
                        });

    }

    @Override
    public void finishLiveRecommend() {
        Log.w(TAG, "finishLiveRecommend: ");
        if (null != mSubLiveRecommend && !mSubLiveRecommend.isUnsubscribed()) {
            mSubLiveRecommend.unsubscribe();
            mSubLiveRecommend = null;
        }

    }

    @Override
    public void createHitChannels() {
        finishHitChannels();
        String liveJson = SPUtils.getInstance(Constant.SP_NAME).getString(Constant.SP_LIVE_JSON);
        if (TextUtils.isEmpty(liveJson)) {
            Log.e(TAG, "createHitChannels: live json is null");
            return;
        }
        final FromLiveBean liveBean = mGson.fromJson(liveJson, FromLiveBean.class);
        String endTime = liveBean.getEndTime();
        long delay = Long.parseLong(endTime) - System.currentTimeMillis();
        Log.w(TAG, "createHitChannels: delay milliseconds:"+delay );
        GetTokenServiceHelper.CaInfo caInfo = mTokenServiceHelper.getCaInfo();
        Log.w(TAG, "call: caid：" + caInfo.caId + "--areaCode:" + caInfo.areaCode + "--serviceId:" + liveBean.getSid());
        //延时获取热播频道
        mSubHitChannels = Api.getInstance().getHitChannels(caInfo.caId, caInfo.areaCode, liveBean.getSid()).
                delay(delay+5000, TimeUnit.MILLISECONDS)   //之后5秒显示
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ResponseBean>() {
                    @Override
                    public void call(ResponseBean responseBean) {
                        if (null != responseBean) {
                            Log.w(TAG, "getHitChannels: url:" + responseBean.getMsg());
                            if (responseBean.getStatus() == 200 || responseBean.getStatus() == 600) {
                                //启动 视图 service
                                startService(responseBean.getMsg());
                            } else {
                                Log.w(TAG, "getHitChannels: status is error! status:" + responseBean.getStatus());
                            }

                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        throwable.printStackTrace();
                    }
                });
    }

    @Override
    public void finishHitChannels() {
        if (null != mSubHitChannels && !mSubHitChannels.isUnsubscribed()) {
            mSubHitChannels.unsubscribe();
            mSubHitChannels = null;
        }
    }

    /**
     * 启动弹窗服务
     *
     * @param url 直播推荐链接&热播频道链接
     */
    private void startService(String url) {
        Intent intentRecommendService = new Intent(Utils.getApp(), RecommendService.class);
        intentRecommendService.putExtra("recommend_url", url);
        Utils.getApp().startService(intentRecommendService);
    }

    @Override
    public void detachView() {
        super.detachView();
        mTokenServiceHelper.unBind(Utils.getApp());
    }

    @Override
    public void onConnected() {
        Log.w(TAG, "onConnected: CA card bind success");
        //获取CA服务链接成功
    }

    @Override
    public void onCaCardChanged() {
        Log.w(TAG, "onCaCardChanged: CA card changed" );
        //CA卡更换回调
    }
}
